<?php

namespace catchAdmin\storehouse\controller;

use catchAdmin\stock\model\WarehouseConfig;
use catchAdmin\storehouse\model\Tray;
use catcher\base\CatchRequest as Request;
use think\Request as LocalRequest;
use catcher\CatchResponse;
use catcher\base\CatchController;
use catchAdmin\storehouse\model\Warehousing as WarehousingModel;
use catchAdmin\storehouse\model\WarehousingSon as WarehousingSonModel;
use think\Exception;
use think\Response;
use catcher\CatchAuth;
use think\facade\Db;
class Warehousing extends CatchController
{
    
    protected $warehousingModel;
    
    /**
     *
     * @time 2022/01/17 12:01
     * @param WarehousingModel $warehousingModel
     * @return mixed
     */
    public function __construct(WarehousingModel $warehousingModel)
    {
        $this->warehousingModel = $warehousingModel;
    }
    
    /**
     * 入库主单列表
     * @time 2022/01/17 12:01
     * @throws \think\db\exception\DbException

     */
    public function index(CatchAuth $auth)
    {
        $user = $auth->user();
        $project_name = request()->param('project_name');
        return CatchResponse::paginate($this->warehousingModel->getList($user['tenant_id'],$project_name,$user['id'],$user['position'],$user['type']));
    }
    
    /**
     * 入库主单添加
     * @time 2022/01/17 12:01
     * @param Request $request
     */
    public function create(CatchAuth $auth,Request $request)
    {
        $params = $request->filterEmptyField()->post();
        $user = $auth->user();
        $params['tenant_id'] = $user['tenant_id'];
        $params['warehousing_id'] = $user['tenant_id'].date('YmdHis').rand(1000,9999);
        $params['project_id'] = $params['project_client'][0];
        $params['project_client'] = $params['project_client'][1];
        if(!empty($params['batch_no'])){
            $info = $this->warehousingModel->where([
                'batch_no'=>$params['batch_no'],
            ])->find();
            if(!empty($info)){
                return CatchResponse::fail('批次号：'.$params['batch_no'].',已存在！');
            }
        }
        $pk =  $this->warehousingModel->storeBy($params);

        $return = $this->warehousingModel->find($pk)->toArray();

//        $return = [
//            'id'=>$pk,
//            'warehousing_id'=> $this->warehousingModel->warehousing_id
//        ];
        return CatchResponse::success($return);
    }
    
    /**
     * 入库主单编辑
     * @time 2022/01/17 12:01
     * @param Request $request
     * @return Response
     */
    public function update(LocalRequest $request) : Response
    {
        $params = $request->post();
        $id = $params['id'];
        unset($params['created_at']);
        $data = $params['project_client'];
        $params['project_client'] = $data[1];
        $params['project_id'] = $data[0];
        if(!empty($params['batch_no'])){
            $info = $this->warehousingModel->where([
                'batch_no'=>$params['batch_no'],
            ])->where('id','<>',$id)->find();
            if(!empty($info)){
                return CatchResponse::fail('批次号：'.$params['batch_no'].',已存在！');
            }
        }
        $this->warehousingModel->updateBy($id, $params);
        $return = $this->warehousingModel->find($id)->toArray();
        return CatchResponse::success($return);
    }
    
    /**
     * 入库主单删除
     * @time 2022/01/17 12:01
     * @param $id
     * @param Request $request
     * @return Response
     */
    public function delete(Request $request) : Response
    {
        $id = $request->post('id');
        $id = is_array($id) ? $id : [$id];
        $warehousingSonModel = new WarehousingSonModel;

        Db::startTrans();
        try {
            foreach ($id as $value){
                $warehousingModel = $this->warehousingModel->find($value);
                $warehousing_id = $warehousingModel->warehousing_id;

                //判断是否子单没有删除干净
                $warehousing_son = $warehousingSonModel
                    ->where('warehousing_id',$warehousing_id)
                    ->select()->toArray();

                if(!empty($warehousing_son)){
                    Db::rollback();
                    throw new Exception('请先删除全部明细单');
                }
                $warehousingModel->delete();
            }
            Db::commit();
        }catch (\Exception $exception) {
            Db::rollback();
            return CatchResponse::fail('删除失败，' . $exception->getMessage());
        }
        return CatchResponse::success('', '删除成功');
    }
    /**
     * 打印
     * @time 2022/01/19 11:52
     * @param Request $request
     * @throws \think\db\exception\DbException
     * @return \think\response\Json
     */
    public function print(Request $request)
    {
        $data = $request->post();
        //主单信息
        $where=[];
        $where['warehousing_id'] = $data['warehousing_id'];
        $warehousing = Db::table('db_warehousing')
            ->where($where)
            ->field('status,warehousing_id,project_id,project_client,settlement,goods_number,customer_business_number,actual_number,customer_order_type,created_at,tenant_id')
            ->find();
        $warehousing['company']=Db::table('users')->where('tenant_id',$warehousing['tenant_id'])->value('merchant_name');
        //项目
        $warehousing['project_id_name'] = Db::table('db_project')->where('project_id',$warehousing['project_id'])->value('project_name');
        //项目和委托人
        $warehousing['project_client_name'] = Db::table('db_project')->where('project_id',$warehousing['project_client'])->value('project_name');
        $warehousing['created_at'] = date('Y-m-d H:i:s',$warehousing['created_at']);
        $warehousing['username'] = Db::table('users')->where('id',$warehousing['tenant_id'])->value('username');
        $warehousing_son_ids=Db::table('db_warehousing_son')->where('warehousing_id',$warehousing['warehousing_id'])->column('warehousing_son_id');
        $where=[];
        $where[]=['a.warehousing_son_id','in',$warehousing_son_ids];
        //$where[]=['a.status','=',0];
        $where[]=['a.deleted_at','=',0];

        if($warehousing['status'] == 1){//全部入库，取stock
            $stock=Db::table('db_stock')
                ->alias('a')
                ->where($where)
                ->select()
                ->toArray();
            foreach ($stock as $k=>$v){
                if($v['Good_Qty']>0){
                    $stock[$k]['goods_status']='Good';
                }elseif ($v['Hold_Qty']>0){
                    $stock[$k]['goods_status']='Hold';
                }elseif ($v['NG_Qty']>0){
                    $stock[$k]['goods_status']='NG';
                }else{
                    $stock[$k]['goods_status']='Good';
                }
            }
        }else{
            $stock = Db::table('db_tray')
                ->alias('a')
                ->where($where)
                ->select()
                ->toArray();
            foreach ($stock as &$value){
//                $value['1'] =
               $product =  Db::table('db_warehousing_product')
                    ->field('goods_id,goods_name,goods_Cname,goods_Ename,manufacturer_id,manufacturer_name,supplier_id,supplier_name,packing_num,unit_name,number,box_number,status,tray_id,specification')
                    ->where(['warehousing_son_id'=>$value['warehousing_son_id'],'deleted_at'=>0,'tray_id'=>$value['tray_id']])
                    ->find();
               $value['goods_name'] = $product['goods_name'];
               $value['specification'] = $product['specification'];
               $value['packing_num'] = $product['packing_num'];
               $value['unit_name'] = $product['unit_name'];
            }
        }

        foreach ($stock as $k=>&$v){
            $v['config_name']=Db::table('db_warehouse_config')->where('config_id',$v['config_id'])->value('name');
        }
        $warehousing['stock']=$stock;
        return  CatchResponse::success($warehousing,'查询成功');
    }
    /**
     * 打印
     * @time 2022/01/19 11:52
     * @param Request $request
     * @throws \think\db\exception\DbException
     * @return \think\response\Json
     */
    public function test(Request $request)
    {
        return  CatchResponse::success('查询成功');
    }

    //返回所有入库单号
    public function getAllWarehousingNo(CatchAuth $auth,Request $request){
        $user = $auth->user();
        $tenant_id = $user['tenant_id'];

        $where = [];
        if($tenant_id !== 0){
            $where[] = ['tenant_id','=',$user->tenant_id];
        }

        $result =  $this->warehousingModel->where($where)->order('id desc')->column('warehousing_id');
        return  CatchResponse::success($result);
    }
    /**
     * 入库表单详情
     */
    public function in_detail(Request $request)
    {
        $params = $request->param();
        $data = Db::table('db_warehousing')
            ->alias('a')
            ->field('a.*')
            ->where('warehousing_id',$params['warehousing_id'])
            ->select()
            ->toArray();

        foreach ($data as &$item){
            $warehousing_config_attribute = explode(',',$item['warehousing_config_attribute']);
            $config_parent_id = (int)Db::table('db_warehouse_config')->where('id',$warehousing_config_attribute[1])->value('parent_id');
            $item['checked_config'] = ['_' . $warehousing_config_attribute[0], $config_parent_id,(int)$warehousing_config_attribute[1]];
            $item['checked_config_status'] =  $warehousing_config_attribute[0];

//            //已经选择后的
//            //所有库位
//            $tray = (new Tray)->alias('t')->field('wc3.name as level_1_name,wc2.name as level_2_name,wc3.address_description')->where([
//                ['warehousing_id','=',$item['warehousing_id']],
//                ['status','in',[0,1]],
//                ['type','=',0]
//            ])
//                ->leftJoin('db_warehouse_config wc','wc.config_id = t.config_id')
//                ->leftJoin('db_warehouse_config wc2','wc.parent_id = wc2.id')
//                ->leftJoin('db_warehouse_config wc3','wc2.parent_id = wc3.id')
//                ->group('wc.parent_id')->select();
//            $item['warehouse_config'] = $tray;

            //调整为 明细单的
            $config_pk_arr = array_column((new WarehousingSonModel)
                ->field("SUBSTRING_INDEX(warehousing_son_config_attribute, ',', -1) as config_pk")
                ->where('warehousing_id',$params['warehousing_id'])->select()->toArray() , 'config_pk');

            $son_select_warehouse_config = (new WarehouseConfig)
                ->alias('wc')
                ->field('wc2.name as level_1_name,wc.name as level_2_name')
                ->leftJoin('db_warehouse_config wc2','wc2.id = wc.parent_id')
                ->where('wc.id','in',$config_pk_arr)
                ->select()->toArray();

            $item['warehouse_config'] = $son_select_warehouse_config;
        }

        return CatchResponse::success($data);
    }

    //项目选择库位（三种状态）
    public function projectWarehouseConfig($project_client_id){
        //$warehouse_project_client = Db::table('db_warehousing')->where('warehousing_id',$id)->value('project_client');
        $project_id = Db::table('db_project')->where('project_id',$project_client_id)->value('id');

        $list =  (new WarehouseConfig)->getProjectLevel3Status($project_id);

        $tree = (new WarehouseConfig)->getProjectLevel2Tree($list);

        $arr = [];
        if(!empty($tree)){
            $usage_name = ['存储区','隔离区','暂放区'];
            $usage_name2 = ['usage_1','usage_2','usage_3'];
            for ($i = 0;$i<=2;$i++){
                $id = $i + 1;
                $arr[$i] = [
                    'id'=>'_' . $id,
                    'name'=> $usage_name[$i],
                    'children'=>$tree[$usage_name2[$i]]
                ];
            }
        }

        return CatchResponse::success($arr,'查询成功');
    }
}